import React, { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, MessagePlugin, Input, Checkbox, Button, FormInstanceFunctions, SubmitContext } from 'tdesign-react';
import { LockOnIcon, UserIcon, BrowseOffIcon, BrowseIcon } from 'tdesign-icons-react';
import classnames from 'classnames';
import { useAppDispatch } from 'modules/store';
import { LoginParams } from 'api/user';
import { login } from '../../../../modules/user';
import Style from './index.module.less';
import { Md5 } from 'ts-md5';

const { FormItem } = Form;

export default function Login() {
  const [showPsw, toggleShowPsw] = useState(false);
  const formRef = useRef<FormInstanceFunctions>();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const onSubmit = async (e: SubmitContext) => {
    if (e.validateResult === true) {
      try {
        const formValue = formRef.current?.getFieldsValue?.(true) || {};
        const params: LoginParams = {
          username: formValue.account,
          password: Md5.hashStr(formValue.password),
        };
        console.log(params);
        await dispatch(login(params));
        MessagePlugin.success('登录成功');

        navigate('/dashboard/base');
      } catch (e: any) {
        console.log(e);
        MessagePlugin.error((e as Error).message);
      }
    }
  };

  return (
    <div>
      <Form
        ref={formRef}
        className={classnames(Style.itemContainer, `login-password`)}
        labelWidth={0}
        onSubmit={onSubmit}
      >
        <>
          <FormItem name='account' rules={[{ required: true, message: '账号必填', type: 'error' }]}>
            <Input size='large' placeholder='请输入账号：admin' prefixIcon={<UserIcon />}></Input>
          </FormItem>
          <FormItem name='password' rules={[{ required: true, message: '密码必填', type: 'error' }]}>
            <Input
              size='large'
              type={showPsw ? 'text' : 'password'}
              clearable
              placeholder='请输入登录密码：admin'
              prefixIcon={<LockOnIcon />}
              suffixIcon={
                showPsw ? (
                  <BrowseIcon onClick={() => toggleShowPsw((current) => !current)} />
                ) : (
                  <BrowseOffIcon onClick={() => toggleShowPsw((current) => !current)} />
                )
              }
            />
          </FormItem>
          <div className={classnames(Style.checkContainer, Style.rememberPwd)}>
            <Checkbox>记住账号</Checkbox>
          </div>
        </>

        <FormItem className={Style.btnContainer}>
          <Button block size='large' type='submit'>
            登录
          </Button>
        </FormItem>
      </Form>
    </div>
  );
}
